<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.stationId ? $t('crud.addTitle') : $t('crud.updateBtn')"
    :close-on-click-modal="false"
    width="900px"
    class="dialog-station-add-or-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      style="min-width: 630px"
      @submit.prevent
    >
      <el-form-item
        :label="$t('station.stationNames')"
        prop="stationName"
        style="width: 530px"
      >
        <el-input
          v-model="dataForm.stationName"
          maxlength="50"
          show-word-limit
          @change="onCheckStationNames"
        />
      </el-form-item>
      <el-form-item
        :label="$t('admin.stationImg')"
        prop="pic"
      >
        <div>
          <img-upload
            ref="delImgRef"
            v-model="dataForm.pic"
          />
          <div
            v-if="dataForm.pic"
            class="default-btn"
            @click="onDeletePic"
          >
            删除
          </div>
        </div>
      </el-form-item>
      <el-form-item
        prop="phone"
        :label="$t('admin.phoNumber')"
        style="width: 430px"
      >
        <el-input
          v-model="dataForm.phone"
          :placeholder="$t('admin.number')"
          maxlength="11"
        />
      </el-form-item>
      <el-form-item
        prop="shopTime"
        style="width: 50%"
      >
        <template #label>
          <div><span class="require">*</span>{{ $t('admin.businTime') }}</div>
        </template>
        <el-time-picker
          v-model="timeDateModeVO.shopTime"
          is-range
          range-separator="-"
          :start-placeholder="$t('admin.businStartTime')"
          :end-placeholder="$t('admin.businEndTime')"
          :placeholder="$t('admin.seleTimeRange')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('admin.timeInter')"
        prop="status"
      >
        <el-radio-group v-model="timeDateModeVO.interval">
          <el-radio :label="1">
            {{ $t('form.day') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('admin.morAndEve') }}
            <el-tooltip
              class="item"
              effect="light"
              :content="$t('admin.dempoint')"
              placement="top"
            >
              <el-icon class="warning">
                <WarningFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
          <el-radio :label="3">
            {{ $t('admin.hour') }}
          </el-radio>
          <el-radio :label="4">
            {{ $t('admin.halfHour') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="stationTime">
        <template #label>
          <div><span class="require">*</span>{{ $t('admin.pickupTime') }}</div>
        </template>
        <el-input
          v-model.number="timeDateModeVO.stationStartTime"
          :placeholder="$t('admin.inputDayNum')"
          style="width: 300px; margin-right: -5px"
        >
          <template #append>
            {{ $t('admin.startPickup') }}
          </template>
        </el-input>
        <el-input
          v-model.number="timeDateModeVO.stationEndTime"
          :placeholder="$t('admin.inPickupEndTime')"
          style="width: 260px"
        >
          <template #append>
            {{ $t('admin.endPickup') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('product.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">
            {{ $t('station.business') }}
          </el-radio>
          <el-radio :label="0">
            {{ $t('station.close') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <template #label>
          <div><span class="require">*</span>{{ $t('admin.pcd') }}</div>
        </template>
        <el-col :span="6">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="city">
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="area">
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              @change="onSelectArea"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item
        :label="$t('address.addr')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          maxlength="100"
          show-word-limit
          @change="onMapLocation(true)"
        >
          <template #append>
            <el-button
              @click="onMapLocation(false)"
            >
              <el-icon><Location /></el-icon>
              {{
                $t('admin.location')
              }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
            @change-lat-lng="onChangeLatLng"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="onSubmit"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { defineExpose } from 'vue'
import { isMobile, isStarMobile } from '@/utils/validate'
const emit = defineEmits(['refreshDataList'])

const timeDateModeVO = ref({
  shopTime: [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)],
  stationStartTime: 0,
  stationEndTime: 7,
  interval: 3
})
// eslint-disable-next-line no-unused-vars
const validateShopTime = (rule, value, callback) => {
  if (!timeDateModeVO.value.shopTime) {
    callback(new Error($t('admin.seleBusTime')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateStationTime = (rule, value, callback) => {
  const reg = /^[0-9]*$/
  if (!reg.test(timeDateModeVO.value.stationStartTime) || !reg.test(timeDateModeVO.value.stationEndTime)) {
    callback(new Error($t('admin.stationA')))
    return
  }
  timeDateModeVO.value.stationStartTime = parseInt(timeDateModeVO.value.stationStartTime) || 0
  timeDateModeVO.value.stationEndTime = parseInt(timeDateModeVO.value.stationEndTime) || 1
  if (!timeDateModeVO.value.stationStartTime && timeDateModeVO.value.stationStartTime !== 0) {
    callback(new Error($t('admin.inStatrPupTime')))
  } else if (!timeDateModeVO.value.stationEndTime && timeDateModeVO.value.stationEndTime !== 0) {
    callback(new Error($t('admin.inPickupEndTime')))
  } else if (timeDateModeVO.value.stationStartTime < 0 || timeDateModeVO.value.stationStartTime > 7) {
    callback(new Error($t('admin.startTimeis') + ' 0-7'))
  } else if (timeDateModeVO.value.stationEndTime < 0 || timeDateModeVO.value.stationEndTime > 7) {
    callback(new Error($t('admin.endTimeis') + ' 1-7'))
  } else if (timeDateModeVO.value.stationStartTime > timeDateModeVO.value.stationEndTime) {
    callback(new Error($t('admin.pickUpTimeError')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validatePhone = (rule, value, callback) => {
  if (dataForm.value.stationId ? !isStarMobile(value) : !isMobile(value)) {
    callback(new Error($t('shop.pleeNormaeNumF')))
  } else {
    callback()
  }
}

const dataRule = {
  stationName: [{ required: true, message: $t('admin.stationNameNoNull'), trigger: 'blur' }],
  shopTime: [{ validator: validateShopTime, trigger: 'blur' }],
  stationTime: [{ validator: validateStationTime, trigger: 'blur' }],
  addr: [{ required: true, message: $t('admin.addrNoNull'), trigger: 'blur' }],
  phone: [{ required: true, message: $t('admin.numberNoNull'), trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  province: [{ required: true, message: $t('admin.seleProv'), trigger: 'change' }],
  city: [{ required: true, message: $t('admin.seleCity'), trigger: 'change' }],
  area: [{ required: true, message: $t('admin.seleDC'), trigger: 'change' }]
}
const visible = ref(false)
const dataForm = ref({
  stationId: null,
  stationName: null,
  pic: null,
  phonePrefix: null,
  phone: null,
  startTime: '',
  endTime: '',
  status: 1,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  lng: null,
  lat: null,
  timeDateModeVO: {}
})
const dataFormRef = ref(null)
const isSubmit = ref(false)
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const show = ref(false)

const init = stationId => {
  dataForm.value.stationId = stationId || 0
  visible.value = true
  show.value = false
  isSubmit.value = false
  nextTick(async () => {
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.value.provinceId = null
    dataForm.value.cityId = null
    dataForm.value.areaId = null
    dataForm.value.phonePrefix = null
    timeDateModeVO.value = {
      shopTime: [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)],
      stationStartTime: 0,
      stationEndTime: 7,
      interval: 3
    }
    onListAreaByParentId().then(({ data }) => {
      provinceList.value = data
      if (dataForm.value.stationId) {
        onGetDataInfo()
      }
    })
  })
}
// 获取店铺详情数据
const onGetDataInfo = () => {
  http({
    url: http.adornUrl('/admin/station/info/' + dataForm.value.stationId),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    timeDateModeVO.value = JSON.parse(data.timeDate)
    onListAreaByParentId(data.provinceId).then(({ data }) => {
      cityList.value = data
    })
    onListAreaByParentId(data?.cityId).then(({ data }) => {
      areaList.value = data
      latLng.value = {
        lng: dataForm.value.lng,
        lat: dataForm.value.lat
      }
    })
  })
}
const onListAreaByParentId = pid => {
  const paramData = {}
  if (!pid) {
    paramData.level = 1
  } else {
    paramData.pid = pid
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}

const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const onSelectProvince = val => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList.value, val)
  dataForm.value.province = curNode.areaName
  if (areas) {
    cityList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const onSelectCity = val => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList.value, val)
  dataForm.value.city = curNode.areaName
  if (areas) {
    areaList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const onSelectArea = val => {
  // 获取区的select
  const { curNode } = onGetCurrentChild(areaList.value, val)
  dataForm.value.area = curNode.areaName
  onMapLocation(true)
}
const onCheckStationNames = () => {
  dataForm.value.stationName = dataForm.value.stationName.trim()
}

// 表单提交
const isEditAddr = ref(false)

const onSubmit = () => {
  dataFormRef.value.validate(valid => {
    if (valid) {
      if (isEditAddr.value) {
        ElMessage.info($t('admin.mapPosi'))
        return
      }
      onGetAreaName()
      dataForm.value.lng = latLng.value.lng
      dataForm.value.lat = latLng.value.lat
      const timeDateMode = timeDateModeVO.value
      if (!timeDateMode.shopTime) {
        ElMessage.error($t('admin.seleBusTime'))
        return
      }
      if (timeDateMode.shopTime[0] instanceof Date) {
        timeDateMode.shopTime[0] = timeDateMode.shopTime[0].getTime()
        timeDateMode.shopTime[1] = timeDateMode.shopTime[1].getTime()
      }
      if (timeDateMode.shopTime[0] >= timeDateMode.shopTime[1]) {
        ElMessage.error($t('admin.busiTimeErr'))
        return
      }
      dataForm.value.timeDate = JSON.stringify(timeDateMode)
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/admin/station'),
        method: dataForm.value.stationId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit.value = false
      })
    }
  })
}

/**
 * 通过省市区id,得到省市区名称
 */
const onGetAreaName = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}

const delImgRef = ref(null)
const onDeletePic = () => {
  dataForm.value.pic = ''
  delImgRef.value.detailImg()
}

// 腾讯地图
const tmapRef = ref(null)
const latLng = ref(null)
const onMapLocation = (isTrue) => {
  let address = ''
  const { provinceId, province, cityId, city, areaId, area, addr } = dataForm.value
  if (isTrue) {
    // 选择省市区时，定位地图
    if (provinceId) {
      address = province
      tmapRef.value.onSetZoom(6)
      if (cityId) {
        address = address + city
        tmapRef.value.onSetZoom(10)
        if (areaId) {
          address = address + area
          tmapRef.value.onSetZoom(18)
          if (addr) {
            // 详细地址
            address = address + addr
            tmapRef.value.onSetZoom(18)
          }
        }
      }
    }
    if (address) {
      tmapRef.value.onGetLocation(address).then(res => {
        onChangeLatLng(res)
      })
    }
  } else {
    if (!provinceId || !cityId || !areaId) {
      dataForm.value.addr = null
      ElMessage({
        message: $t('admin.selePCD'),
        type: 'error',
        duration: 1000
      })
      return
    }
    tmapRef.value.onGetAddress(latLng.value).then(res => {
      dataForm.value.addr = res.formatted_addresses?.standard_address || res.address
    })
    tmapRef.value.onSetZoom(18)
  }
}

// 修改经纬度
const onChangeLatLng = (latLngInfo) => {
  const { lng, lat } = latLngInfo
  latLng.value = latLngInfo
  dataForm.value.shopLng = lng
  dataForm.value.shopLat = lat
}

defineExpose({ init })
</script>
<style lang="scss" scoped>
.dialog-station-add-or-update {
  .map {
    width: 100%;
    height: 500px;
  }
  .require {
    color: #f56c6c;
    margin-right: 4px;
  }
  .warning{
    vertical-align: text-bottom;
  }
}
</style>
